import "package:flutter/material.dart";

// 非状态组件
class UseStatelessWidget extends StatelessWidget {
  int count = 0;
  UseStatelessWidget({super.key});
  @override
  Widget build(BuildContext context) {
    return SizedBox(
        width: double.infinity,
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Text("current Count: $count"),
            const SizedBox(
              height: 20,
            ),
            ElevatedButton(
                onPressed: () {
                  count++; //非状态组件，值改变，但显示不变
                },
                child: const Text('点击'))
          ],
        ));
  }
}

// 状态组件
class UseStatefulWidget extends StatefulWidget {
  const UseStatefulWidget({super.key});

// 状态组件必须有createState方法，返回状态类，状态类中包含setState用于修改状态触发rebuild
  @override
  State<UseStatefulWidget> createState() {
    return _StatefulWidgetState();
  }
}

class _StatefulWidgetState extends State<UseStatefulWidget> {
  int count = 0;
  @override
  Widget build(BuildContext context) {
    return SizedBox(
        width: double.infinity,
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Text("current Count: $count"),
            const SizedBox(
              height: 20,
            ),
            ElevatedButton(
                onPressed: () {
                  // 通过setState 改变变量
                  setState(() {
                    count++;
                  });
                },
                child: const Text('点击'))
          ],
        ));
  }
}

// 点击新增列表元素
class UseStatefulWidgetList extends StatefulWidget {
  const UseStatefulWidgetList({super.key});

  @override
  State<StatefulWidget> createState() {
    return _StatefulWidgetListState();
  }
}

class _StatefulWidgetListState extends State<UseStatefulWidgetList> {
  final List<String> list = ["label0"];
  @override
  Widget build(BuildContext context) {
    return Column(
      children: [
        ElevatedButton(
            onPressed: () {
              setState(() {
                list.add("label${list.length}");
              });
            },
            child: const Text("新增")),
        Expanded(
            flex: 1,
            child: ListView.builder(
              itemCount: list.length,
              itemBuilder: (context, index) {
                return ListTile(
                  leading: const Text("leading"),
                  title: Text(list[index]),
                  trailing: const Text("trailing"),
                );
              },
            ))
      ],
    );
  }
}
